'''
Copyright: 
Descripttion: 
version: 
Author: chengx
Date: 2021-01-13 16:54:07
LastEditors: chengx
LastEditTime: 2021-01-15 14:07:18
'''
import cv2
import matplotlib.pyplot as plt
import numpy as np
import math


def calc_hist():
    img = cv2.imread('20201210_3.bmp',0)

    cv2.imshow('image',img)
    cv2.waitKey(0)

    hist_cv = cv2.calcHist([img],[0],None,[256],[0,256])

    for i in range(0,256):
        if hist_cv[i] !=0:
            print(hist_cv[i])

    p = hist_cv/(640*640)
    plt.subplot(111)
    plt.plot(p)
    plt.show()
    E = 0
    for i in range(len(p)):
        if(p[i] == 0):
            E = E
        else:
            E = float(E - p[i] * (math.log(p[i]) / math.log(2.0)))
    print(E)

def calc_array():
    # img = np.zeros([16,16]).astype(np.uint8)
    # img[0:8][:]=255
    a= [i  for i in range(256)]
    img = np.array(a).astype(np.uint8).reshape(16,16)
    hist_cv = cv2.calcHist([img],[0],None,[256],[0,256])
    print(hist_cv)
    for i in range(256):
        if hist_cv[i] !=0:
            print(hist_cv[i])
    plt.subplot(111)
    plt.plot(hist_cv)
    plt.show()
    P = hist_cv/(len(img)*len(img[0]))
    E = np.sum([p *np.log2(1/p) for p in P])
    print(E)


def calc_2D_Entropy():
    '''
    邻域 3*3的小格子
     __ __ __
    |__|__|__|
    |__||||__|
    |__|__|__|
    角点
     __ __
    ||||__|
    |__|__|
    边
     __ __
    |  |__|
    ||||__|
    |__|__|
    '''
    a= [i  for i in range(256)]
    img = np.array(a).astype(np.uint8).reshape(16,16)

    N = 1
    S=img.shape
    IJ = []
    #计算j
    for row in range(S[0]):
        for col in range(S[1]):
            Left_x=np.max([0,col-N])
            Right_x=np.min([S[1],col+N+1])
            up_y=np.max([0,row-N])
            down_y=np.min([S[0],row+N+1])
            region=img[up_y:down_y,Left_x:Right_x] # 九宫格区域
            j = (np.sum(region) - img[row][col])/((2*N+1)**2-1)
            IJ.append([img[row][col],j])
    print(IJ)
    # 计算F(i,j)
    F=[]
    arr = [list(i) for i in set(tuple(j) for j in IJ)] #去重，会改变顺序，不过此处不影响
    for i in range(len(arr)):
        F.append(IJ.count(arr[i]))
    print(F)
    # 计算pij
    P=np.array(F)/len(F)

    # 计算熵
    E = np.sum([p *np.log2(1/p) for p in P])
    print(E)

calc_array()

